package jimmy.com.server.fragment;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.jimmy.common.base.app.TemplateFragment;
import com.jimmy.common.base.net.BaseResponse;
import com.jimmy.common.listener.OnResponseListener;
import com.jimmy.common.util.SharedUtils;
import com.jimmy.common.util.ToastUtils;

import java.util.List;

import jimmy.com.server.R;
import jimmy.com.server.activity.LoginActivity;
import jimmy.com.server.adapter.SelectStoreAdapter;
import jimmy.com.server.api.WebApi;
import jimmy.com.server.config.ApiCode;
import jimmy.com.server.config.SharedKey;
import jimmy.com.server.config.WorkerConfig;
import jimmy.com.server.data.Store;
import jimmy.com.server.data.User;
import jimmy.com.server.dialog.ZHUploadDialog;

/**
 * Created by Administrator on 2017/5/24.
 */
public class ZHMainFragment extends TemplateFragment implements View.OnClickListener {

    private EditText etScanCode, etUserId, etLength, etWidth, etHeight, etWeight;
    private Spinner srSelectStore;

    @Nullable
    @Override
    protected View initContentView(LayoutInflater inflater, @Nullable ViewGroup container) {
        return inflater.inflate(R.layout.fragment_zh_main, container, false);
    }

    @Override
    protected void initView() {
        hideLeftButton();
        etScanCode = searchViewById(R.id.etScanCode);
        etUserId = searchViewById(R.id.etUserId);
        etLength = searchViewById(R.id.etLength);
        etWidth = searchViewById(R.id.etWidth);
        etHeight = searchViewById(R.id.etHeight);
        etWeight = searchViewById(R.id.etWeight);
        srSelectStore = searchViewById(R.id.srSelectStore);
        searchViewById(R.id.btnUpload).setOnClickListener(this);
        searchViewById(R.id.btnLogout).setOnClickListener(this);
        initSpinnerStore();
        etScanCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
    }

    private void initSpinnerStore() {
        List<Store> stores = WorkerConfig.getInstance().getStores();
        srSelectStore.setAdapter(new SelectStoreAdapter(mContext, stores, R.layout.list_item_select_store));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnUpload:
                check();
                break;
            case R.id.btnLogout:
                logout();
                break;
        }
    }

    private void check() {
        final String code = etScanCode.getText().toString();
        final String userId = etUserId.getText().toString();
        final String length = etLength.getText().toString();
        final String width = etWidth.getText().toString();
        final String height = etHeight.getText().toString();
        final String weight = etWeight.getText().toString();
        final String storeId = String.valueOf(((Store) srSelectStore.getSelectedItem()).store_id);
        if (TextUtils.isEmpty(code) || TextUtils.isEmpty(length) || TextUtils.isEmpty(width) || TextUtils.isEmpty(height) || TextUtils.isEmpty(weight)) {
            ToastUtils.showShortToast(mActivity, R.string.zh_info_is_empty);
        } else if (WorkerConfig.getInstance().getStore(Integer.parseInt(storeId)) == null) {
            ToastUtils.showShortToast(mActivity, R.string.zh_store_empty);
        } else {
            searchViewById(R.id.btnUpload).setEnabled(false);
            if (TextUtils.isEmpty(userId)) {
                ZHUploadDialog dialog = new ZHUploadDialog(mActivity);
                dialog.setData(code, userId, "未知", length, width, height, weight, storeId);
                dialog.setOnConfirmListener(new ZHUploadDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        upload(code, userId, length, width, height, weight, storeId, 0);
                    }

                    @Override
                    public void onConfirmError() {
                        upload(code, userId, length, width, height, weight, storeId, 1);
                    }
                });
                dialog.show();
                searchViewById(R.id.btnUpload).setEnabled(true);
                return;
            }
            WebApi.checkUser(userId, new OnResponseListener<BaseResponse<User>>() {
                @Override
                public void onResponse(BaseResponse<User> response) {
                    if (response.getCode() == ApiCode.SUCCESS && response.getData() != null) {
                        ZHUploadDialog dialog = new ZHUploadDialog(mActivity);
                        dialog.setData(code, userId, response.getData().real_name, length, width, height, weight, storeId);
                        dialog.setOnConfirmListener(new ZHUploadDialog.OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                upload(code, userId, length, width, height, weight, storeId, 0);
                            }

                            @Override
                            public void onConfirmError() {
                                upload(code, userId, length, width, height, weight, storeId, 1);
                            }
                        });
                        dialog.show();
                    } else {
                        ToastUtils.showShortToast(mActivity, R.string.zh_user_no_exist);
                    }
                    searchViewById(R.id.btnUpload).setEnabled(true);
                }

                @Override
                public void onError(VolleyError error) {
                    super.onError(error);
                    ToastUtils.showShortToast(mActivity, R.string.zh_user_no_exist);
                    searchViewById(R.id.btnUpload).setEnabled(true);
                }
            });
        }
    }

    private void upload(String code, String userId, String length, String width, String height, String weight, String storeId, int isProblem) {
        WebApi.uploadZH(code, userId, length, width, height, weight, storeId, isProblem, new OnResponseListener<BaseResponse<String>>() {
            @Override
            public void onResponse(BaseResponse<String> response) {
                if (response.getCode() == ApiCode.SUCCESS) {
                    ToastUtils.showShortToast(mActivity, R.string.zh_upload_success);
                    clearText();
                } else {
                    ToastUtils.showShortToast(mActivity, R.string.zh_upload_failed);
                }
            }

            @Override
            public void onError(VolleyError error) {
                super.onError(error);
                ToastUtils.showShortToast(mActivity, R.string.zh_upload_failed);
            }
        });
    }

    private void clearText() {
        etScanCode.getText().clear();
        etUserId.getText().clear();
        etLength.getText().clear();
        etWidth.getText().clear();
        etHeight.getText().clear();
        etWeight.getText().clear();
        etScanCode.requestFocus();
    }

    private void logout() {
        SharedUtils.putBoolean(mActivity, SharedKey.ZH_IS_LOGIN, false);
        Intent intent = new Intent(mActivity, LoginActivity.class);
        mActivity.startActivity(intent);
        mActivity.finish();
    }

}
